package com.cloudtcm.controller.admin;

import com.cloudtcm.constant.JwtClaimsConstant;
import com.cloudtcm.dto.EmployeeDTO;
import com.cloudtcm.dto.EmployeeLoginDTO;
import com.cloudtcm.entity.Employee;
import com.cloudtcm.properties.JwtProperties;
import com.cloudtcm.result.Result;
import com.cloudtcm.serviece.EmployeeService;
import com.cloudtcm.utils.JwtUtil;
import com.cloudtcm.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@Api(tags = "员工相关接口")
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("员工登录")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    /**
     * 员工注册
     * @param employeeDTO
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("员工注册")
    public Result save(@RequestBody EmployeeDTO employeeDTO){
        log.info("员工注册:{}", employeeDTO);

        employeeService.save(employeeDTO);
        return Result.success();
    }

    /**
     * 更新员工信息
     * @param employeeDTO
     * @return
     */
    @PutMapping("/update")
    @ApiOperation("更新员工信息")
    public Result update(@RequestBody EmployeeDTO employeeDTO){
        log.info("更新员工信息:{}",employeeDTO);
        employeeService.update(employeeDTO);
        return Result.success();
    }
}
